package com.huahai.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huahai.constant.RedisConstant;
import com.huahai.pojo.entity.User;
import com.huahai.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务预热缓存
 */
@Component
@Slf4j
public class PreCacheTask {

    private static final long RECOMMEND_EXPIRE_TIME_MINUTE = 10L;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    // 缓存主要的用户
    // TODO 可以运用MYSQL的功能标记，标记重点用户，不要把数组写死
    private List<Long> mainUserList = Arrays.asList(4L);

    private static final String LOCK_KEY = "lock";

    /**
     * 预热主要用户推荐信息的缓存
     */
    @Scheduled(cron = "0 0 0 * * *") // 指定每天0点0分执行该预热任务
    private void preCacheRecommendUser() {

        // 获取分布式锁锁
        String lockKey = RedisConstant.PROJECT_KEY + RedisConstant.TASK_KEY + RedisConstant.PRECACHE_KEY + LOCK_KEY;
        RLock lock = redissonClient.getLock(lockKey);

        long waitTime = 0L;
        long leaseTime = 30L;

        try {
            if (lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS)) {
                for (Long userId : mainUserList) {
                    // 查询数据库
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userList = userService.page(new Page<>(1, 20), queryWrapper);

                    String prefixKey = RedisConstant.PROJECT_KEY;
                    String key = String.format(prefixKey + RedisConstant.USER_KEY + "recommend:%s", userId);

                    // 将查询到的用户信息缓存到redis中
                    try {
                        redisTemplate.opsForValue().set(key, userList, RECOMMEND_EXPIRE_TIME_MINUTE, TimeUnit.HOURS);
                    } catch (Exception e) {
                        log.error("redis preCache error:", e);
                    }
                }

            }
        } catch (InterruptedException e) {
            log.error("preCacheTask error:", e);
        } finally {
            // 如果释放的锁属于当前线程就释放锁
            boolean isThreadLock = lock.isHeldByCurrentThread();
            if(isThreadLock){
                lock.unlock();
            }
        }

    }
}
